import { IJuggle } from "../Interfaces/IJuggle";
import { getTimer } from "../Utility/dx/getTimer";

export class JuggleManager
{
    private static juggles:Array<IJuggle> = [];
    private static isStartJuggle:boolean = false;
    private static currentJuggleTime:number = 0;
    private static lastJuggleTime:number = 0;
    private static interval:number = 20;
    private static _timeID:number = 0;

    public static AddJuggle(juggle:IJuggle):void
    {
        if(this.juggles.indexOf(juggle)==-1)
        {
            this.juggles.push(juggle);
            this.startJuggle();
        }
    }
    public static RemoveJuggle(juggle:IJuggle):void
    {
        let index = this.juggles.indexOf(juggle);
        if(index==-1)return;
        this.juggles.splice(index,1);
        if(this.juggles.length==0)this.stopJuggle();
    }
    /**开启**/
    private static startJuggle():void
    {
        if(this.isStartJuggle)return;
        this.isStartJuggle = true;
        this.lastJuggleTime = getTimer();
        this._timeID = setInterval(() =>
        {
            JuggleManager.onJuggle();
        }, this.interval);
    }
    /**停止**/	
    private static stopJuggle():void
    {
        if(this.isStartJuggle==false)return;
        this.isStartJuggle = false;
        if(this._timeID!=0)clearInterval(this._timeID);
        this._timeID = 0;
    }
    private static onJuggle(evt?:any):void
    {
        if(this.isStartJuggle==false)return;
        var currentTime:number = getTimer();
        this.currentJuggleTime = currentTime-this.lastJuggleTime;
        if(this.currentJuggleTime>1000)this.currentJuggleTime = 1000;
        this.lastJuggleTime = currentTime;
        for (let i = 0; i < this.juggles.length; i++) 
            this.juggles[i].onJuggle(this.currentJuggleTime);
    }
}